import matplotlib.pyplot as plt
from sklearn import neighbors
from sklearn.datasets.samples_generator import make_blobs
from sklearn.cluster import AffinityPropagation
import scipy.io as scio
from sklearn.decomposition import PCA
from numpy import unique
from numpy import where
import random
import itertools

import numpy as np
import h5py as h5
import pandas as pd
from multiprocessing import Queue
import multiprocessing
from heapq import *
import math
def accuracy(prediction, labels):
    return np.mean(np.sqrt(np.sum((prediction - labels) ** 2, 1)))
def knn_reg(off_rss,off_loc,trace,rss,k):
    # uniform 本节点所有邻节点投票权重一样
    # weight 投票权重
    knn_reg = neighbors.KNeighborsRegressor(k, weights='uniform', metric='euclidean')
    # print(knn_reg)
    knn_reg.fit(off_rss, off_loc)
    predictions = knn_reg.predict(rss)
    max_pre = 0
    for i in range(predictions.shape[0]):
        dot = predictions[i] - trace[i]
        dis = math.sqrt(dot[0] * dot[0] + dot[1] * dot[1])
        if dis > max_pre:
            max_pre = dis
    print(max_pre)
    # for pre in predictions:
    #     if pre > max_pre:
    #         max_pre = pre
    # print(predictions - trace)
    # plt_loc_rea(predictions,trace,name='预测后的点与真实点对比'+str(k))
    acc = accuracy(predictions, trace)
    print("acc:", acc , "m")
    # for i in range(len(predictions)):
    #     print(predictions[i],trace[i])
    return acc / 100
if __name__ == '__main__':
    path16 = 'D:/Python workspace/chan/channels_July16.mat'
    data16 = h5.File(path16, 'r')
    off_rss = data16['RSSI'][:]
    off_xy = data16['labels'][:]
    off_rss = off_rss.T
    off_xy = off_xy.T
    off_rss = off_rss[::100]
    off_xy = off_xy[::100]
    off_rss = off_rss.T
    off_xy = off_xy.T
    # 在线数据
    path18 = 'D:/Python workspace/chan/channels_July18.mat'

    data18 = h5.File(path18, 'r')
    # print(data18['RSSI'][1:2][0:100])
    on_rss = data18['RSSI'][:]
    on_xy = data18['labels'][:]
    off_rss = off_rss.T
    off_xy = off_xy.T
    on_rss = on_rss.T
    on_xy = on_xy.T

    print(off_rss.shape)
    print(off_xy.shape)
    print(on_xy.shape)
    print(on_rss.shape)

    for i in range(4,50):
        print('第',i,'次K值')
        knn_reg(off_rss, off_xy, on_xy, on_rss,i)
    data_off_rss_idw = pd.read_csv('data/rss/off_rss_idw30_num_20000.csv')
    data_off_xy_idw = pd.read_csv('data/xy/off_xy_idw30_num_20000.csv')

    del data_off_xy_idw['Unnamed: 0']
    del data_off_rss_idw['Unnamed: 0']

    data_off_rss_idw = np.array(data_off_rss_idw)
    data_off_xy_idw = np.array(data_off_xy_idw)
    # data_off_rss_idw = data_off_rss_idw.T
    # data_off_xy_idw = data_off_xy_idw.T

    # on_rss = on_rss.T
    # on_xy = on_xy.T
    print(data_off_rss_idw.shape)
    print(data_off_xy_idw.shape)
    print(on_xy.shape)
    print(on_rss.shape)

    for i in range(4,50):
        print('第',i,'次K值')
        knn_reg(data_off_rss_idw, data_off_xy_idw, on_xy, on_rss, i)

